/*
Copyright (C) 2014 Yuvraj Singh Babrah

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */


package design;

import code.ValidateTokens;
import com.alee.laf.WebLookAndFeel;
import java.io.File;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 *
 * @author Manhattan
 */
public class AcceptTokens extends javax.swing.JFrame {
    /* props */
    public static JLabel errorLabel;
    public static JButton validateButtonStatic;
        
    /**
     * Creates new form AcceptTokens
     */
    public AcceptTokens() {
        int result = checkFiles();
        if(result != 0) {
            JOptionPane.showMessageDialog(null, "lib folder missing! Please make sure the application is in the same path as the lib folder.\nOtherwise Download the application again.", "Folder Missing", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
        splash();
        initComponents();
        setIcon();
        customChanges();
        assignStaticVariables();
    }
    
    /**
     * @return 
     */
    public int checkFiles() {
        String dir = System.getProperty("user.dir");
        dir += "\\lib";
        File currDir = new File(dir);
        boolean check = false;
        if(currDir.exists()) {
            String[] files = currDir.list();
            int count = files.length;
            if(count == 2) {
                check = true;
            }
            else {
                check = false;
            }
        }
        else {
            check = false;
        }
        if(check)
            return 0;
        else 
            return 1;
    }
    
    /**
     * Displays splash screen on start
     */
    public void splash() {
        new Splash();
    }
    
    /**
     * setIcon
     */
    public void setIcon() {
        try{
            URL iconURL = getClass().getResource("/resources/icon_32.png");
            ImageIcon icon = new ImageIcon(iconURL);
            this.setIconImage(icon.getImage());
        } catch(Exception e) { }
    }
    
    /**
     * Make custom changes in the design
     */
    public void customChanges() {
        this.setContentPane(new JLabel(new ImageIcon(AcceptTokens.class.getClassLoader().getResource("resources/back.jpg"))));
        this.setLocationRelativeTo(null);
        this.add(jLabel1);
        this.add(jLabel2);
        this.add(tokenValue);
        this.add(validateButton);
        this.add(jSeparator1);
        this.add(jLabel3);
        this.add(jLabel4);
        this.add(errorMsg);
    }

    /**
     * assign to static props declared at the start **imp
     */
    public void assignStaticVariables() {
        this.validateButtonStatic = validateButton;
        this.errorLabel = errorMsg;
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tokenValue = new javax.swing.JTextField();
        validateButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        error = new javax.swing.JLabel();
        errorMsg = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("The Albums Downloader");
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Segoe UI Light", 0, 75)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("hi! enter");

        jLabel2.setFont(new java.awt.Font("Segoe UI Light", 0, 75)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("token value");

        tokenValue.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tokenValueKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tokenValueKeyTyped(evt);
            }
        });

        validateButton.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N
        validateButton.setText("Validate");
        validateButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                validateButtonMouseClicked(evt);
            }
        });
        validateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                validateButtonActionPerformed(evt);
            }
        });

        jLabel3.setBackground(new java.awt.Color(255, 255, 255));
        jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(51, 51, 51));
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Created with love by Yuvraj Singh Babrah");

        jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(51, 51, 51));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("The Albums Downloader v1.0");

        error.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N
        error.setForeground(new java.awt.Color(255, 255, 255));

        errorMsg.setFont(new java.awt.Font("Segoe UI", 1, 11)); // NOI18N
        errorMsg.setForeground(new java.awt.Color(255, 255, 255));
        errorMsg.setText("enter the token value obtained via the web app");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addComponent(tokenValue)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(error, javax.swing.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
                            .addComponent(errorMsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(validateButton))
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(0, 166, Short.MAX_VALUE))
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(95, 95, 95)
                .addComponent(jLabel1)
                .addGap(0, 0, 0)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tokenValue, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(validateButton)
                    .addComponent(error)
                    .addComponent(errorMsg))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 228, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addComponent(jLabel4)
                .addGap(0, 0, 0)
                .addComponent(jLabel3)
                .addGap(24, 24, 24))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void validateButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_validateButtonMouseClicked
        // not needed any more
    }//GEN-LAST:event_validateButtonMouseClicked

    private void validateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_validateButtonActionPerformed
        // TODO validate tokens via fb api
        int errorFlag = 0;
        String tokenValue = this.tokenValue.getText();
        tokenValue = tokenValue.trim();
        if(tokenValue.length() <= 0) {
            errorFlag ++;
        }
        if(errorFlag != 0) {
            this.errorMsg.setText("Please enter a token value!");
        }
        else {
            this.errorMsg.setText("working ...");
            this.validateButton.setEnabled(false); // disable button
            new ValidateTokens(this, tokenValue).start(); // invoke thread
        }
    }//GEN-LAST:event_validateButtonActionPerformed

    private void tokenValueKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tokenValueKeyTyped
        // not needed any more
    }//GEN-LAST:event_tokenValueKeyTyped

    private void tokenValueKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tokenValueKeyPressed
        // TODO validate tokens via fb api
        if(evt.getKeyCode() == 10) { // enter key
            if(!this.validateButton.isEnabled()) {
                return;
            }
            int errorFlag = 0;
            String tokenValue = this.tokenValue.getText();
            tokenValue = tokenValue.trim();
            if(tokenValue.length() <= 0) {
                errorFlag ++;
            }
            if(errorFlag != 0) {
                this.errorMsg.setText("Please enter a token value!");
            }
            else {
                this.errorMsg.setText("working ...");
                this.validateButton.setEnabled(false); // disable button
                new ValidateTokens(this, tokenValue).start(); // invoke thread
            }
        }
    }//GEN-LAST:event_tokenValueKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set WebLnF */
        try {
            WebLookAndFeel.install();
        }catch (Exception ex) {}

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AcceptTokens().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel error;
    private javax.swing.JLabel errorMsg;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField tokenValue;
    private javax.swing.JButton validateButton;
    // End of variables declaration//GEN-END:variables
}
